import 'package:aitao_flutter/routes/routes.dart';
import 'package:aitao_flutter/utils/log_utils.dart';
import 'package:aitao_flutter/utils/oss_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../model/user_data.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../utils/alert_utils.dart';
import '../../utils/sp_utils.dart';

class PhotoAlbumController extends GetxController {
  UserData? userData2;

  @override
  void onInit() {
    super.onInit();
    getUserData();
  }

  void getUserData() async {
    var result = await RequestManager().post(API.myInfo);
    if (result != null && result['code'] == 0) {
      UserData userData = UserData.fromJson(result['data']);
      SpUtil.saveUserData(userData);
      WJLogUtils.wjLog(result);
      userData2 = userData;
      update();
    }
  }

  void updateAvatar() async {
    // 检测权限
    checkPermission(Get.context!);
    // AlertUtils().showImageSheet(Get.context!, (e) {
    //   if (e == '从手机相册选择') {
    //     pickPhoto(0);
    //   }
    // }, canPhoto: false);
  }

  void addPhoto() {
    AlertUtils().showImageSheet(Get.context!, (e) {
      if (e == '从手机相册选择') {
        pickPhoto(1);
      }
    }, canPhoto: false);
  }

  void deletePhoto(int index) {
    debugPrint(index.toString());
    userData2?.userinfo?.albumList!.removeAt(index);
    update();
  }

  /// 选择照片
  /// 0: 头像 1:相册
  pickPhoto(int type) async {
    AssetPickerConfig config =
        const AssetPickerConfig(maxAssets: 1, requestType: RequestType.image);
    final List<AssetEntity>? entitys =
        await AssetPicker.pickAssets(Get.context!, pickerConfig: config);
    // final List<AssetEntity>? entitys = await AssetPicker.pickAssets(context)
    if (entitys == null) return;
    EasyLoading.show(status: '上传中...');

    try {
      String result = await UploadOss.uploadImages(entitys);
      EasyLoading.dismiss();

      if (type == 0) {
        debugPrint('头像上传结果result:$result');
        if (result != '') {
          userData2!.userinfo?.avatar = result;
        }
      } else {
        debugPrint('相册上传结果result:$result');
        if (result != '') {
          userData2!.userinfo?.albumList?.add(result);
          debugPrint(userData2!.userinfo?.albumList.toString());
        }
      }
      update();
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }

    //遍历
    // for (var entity in entitys) {
    //   File? imgFile = await entity.file;
    //   if (imgFile != null) {
    //     debugPrint('图片地址:${imgFile.path}');
    //     // 1.服务器Api上传图片
    //     var result = await RequestManager().upLoadSingleFile(imgFile.path,UploadImagesType.album);
    //     print('result:${result}');
    //     if (result != null && result['code'] == 200) {
    //       String avaterUrl = result['data'];
    //       if (avaterUrl.isNotEmpty) {
    //         print('avaterUrl:${avaterUrl}');
    //         // updateAvater(avaterUrl);
    //       }
    //   }
    // }
  }

  void checkPermission(BuildContext context) async {
    Permission permission = Permission.storage;
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      AlertUtils().showImageSheet(Get.context!, (e) {
        if (e == '从手机相册选择') {
          RequestManager.updateOssParams();
          pickPhoto(0);
        }
      }, canPhoto: false);
    } else if (status.isDenied) {
      //权限拒绝， 需要区分IOS和Android，二者不一样
      requestPermission(permission);
    } else if (status.isPermanentlyDenied || status.isRestricted) {
      //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
      showDialog<String>(
        context: Get.context!,
        builder: (BuildContext context) => AlertDialog(
          title: const Text('你已关闭手机相册相册权限'),
          content: const Text('请到手机设置开启相册权限'),
          actions: <Widget>[
            // if user deny again, we do nothing
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('不开启'),
            ),

            // if user is agree, you can redirect him to the app parameters :)
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                openAppSettings();
              },
              child: const Text('去开启'),
            ),
          ],
        ),
      );
    } else {
      //第一次申请
      requestPermission(permission);
    }
  }

  void requestPermission(Permission permission) async {
    //发起权限申请
    PermissionStatus status = await permission.request();
    // 返回权限申请的状态 status
    if (status.isPermanentlyDenied) {
      //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
      showDialog<String>(
        context: Get.context!,
        builder: (BuildContext context) => AlertDialog(
          title: const Text('你已关闭手机相册相册权限'),
          content: const Text('请到手机设置开启相册权限'),
          actions: <Widget>[
            // if user deny again, we do nothing
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('不开启'),
            ),
            // if user is agree, you can redirect him to the app parameters :)
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                openAppSettings();
              },
              child: const Text('去开启'),
            ),
          ],
        ),
      );
    }
  }

  void bottomItemClick(String title) async {
    if (title == '昵称') {
      var newNickName = await Get.toNamed(Routes.editNamePage);
      userData2?.userinfo?.nickname = newNickName;
      update();
      // print('接收到了上个页面的结果:${newNickName}');
    } else if (title == '生日') {
      AlertUtils().showBottomDateSheet(Get.context!, (b) {
        userData2?.userinfo?.birthday = b;
        update();
      }, currentBirthday: userData2?.userinfo?.birthday ?? '1990-01-01');
    }
  }

  void submitClick() async {
    if (userData2 == null) return;
    if (userData2!.userinfo == null) return;
    String albums = '';
    if (userData2!.userinfo!.albumList!.isNotEmpty) {
      albums = userData2!.userinfo!.albumList!.join(',');
    }
    Map params = {
      'nickname': userData2!.userinfo!.nickname,
      'birthday': userData2!.userinfo!.birthday,
      'avatar': userData2!.userinfo!.avatar,
      'albums': albums
    };
    debugPrint('参数:$params');
    var result =
        await RequestManager().post(API.updateUserInfo, params: params);
    if (result != null && result['code'] == 0) {
      EasyLoading.showToast('提交成功,请等待审核结果');
      Get.back();
    }
  }
}
